package net.j4love.netty.inaction.c9;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author he peng
 * @create 2018/6/14 11:44
 * @see
 */
public class FixedLengthFrameDecoder extends ByteToMessageDecoder {

    private final Integer frameLength;

    public FixedLengthFrameDecoder(Integer frameLength) {
        if (frameLength == null) {
            throw new IllegalArgumentException("frameLength == null");
        }
        if (frameLength <= 0) {
            throw new IllegalArgumentException("frameLength <= 0");
        }
        this.frameLength = frameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        while (in.readableBytes() >= frameLength) {
            System.out.println("read " + frameLength + " bytes");
            ByteBuf buf = in.readBytes(frameLength);
            out.add(buf);
        }
    }
}
